import os
from openai import OpenAI

class OpenAIModel:
    """OpenAI模型调用类"""
    def __init__(self):
        api_url = os.getenv("API_URL", "https://api.openai.com/v1/chat/completions")
        model_name = os.getenv("MODEL_NAME", "gpt-3.5-turbo")
        api_key = os.getenv("API_KEY")
        
        if not api_key:
            raise ValueError("API_KEY未配置，请在.env文件中设置")
        
        self.client = OpenAI(
            base_url=api_url,
            api_key=api_key
        )
        self.model_name = model_name
        self.timeout = 30  # 设置超时时间
    
    def generate_text(self, prompt, max_tokens=500):
        """调用OpenAI模型生成文本"""
        try:
            response = self.client.chat.completions.create(
                model=self.model_name,
                messages=[{"role": "user", "content": prompt}],
                max_tokens=max_tokens,
                temperature=0.7,
                extra_body={"enable_thinking": False} # 百炼 qwen3-32b 思考类模型需要增加参数
            )
            return response.choices[0].message.content.strip()
        except Exception as e:
            print(f"OpenAI模型调用错误: {e}")
            # 如果API调用失败，返回None
            return None